package com.mysql.jdbc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author gaobiao
 *
 */
public class AutoSSH {
	private static Connection conn = null;
	// 数据库连接配置
	private static String host = "localhost";
	private static String port = "3306";
	private static String dbname = "vschool";
	private static String username = "root";
	private static String password = "system";
	// java文件页头设置
	private static boolean hasHead = false;
	private static String author = "GB";
	//生成文件保存位置根目录（需手动创建）
	private static String path = "E:\\android\\";
	

	private static String tablename = "b_student";
	private static String baseName = "Student";
	private static String basePackage = "com.school.base";

	public static Connection getConnectionByJDBC() {
		try {
			// 装载驱动包类
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("装载驱动包出现异常!请查正！");
			e.printStackTrace();
		}
		try {
			/**
			 * 建立jdbc连接，但要注意此方法的第一个参数， 如果127.0.0.1出现CommunicationsException异常，
			 * 可能就需要改为localhost才可以
			 **/
			// jdbc:mysql://localhost:3306/test，test是数据库
			conn = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + dbname, username, password);
		} catch (SQLException e) {
			System.out.println("链接数据库发生异常!");
			e.printStackTrace();
		}
		return conn;
	}

	public void test() throws IOException {
		String modelPackage = basePackage + ".model";
		String daoPackage = basePackage + ".dao";
		String actionPackage = basePackage + ".action";

		String sql = "select * from " + tablename;
		String tab = "\t";
		Date date = new Date();
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = dateformat.format(date);
		String fileTop = "";
		if (hasHead) {
			fileTop = "/**\r\n *Copyright 2013 \r\n *All Right Reserved\r\n *Author ：" + author + "\r\n *编码日期格式：" + dateStr + "\r\n */\r\n";
		}
		getConnectionByJDBC();
		try {
			// 创建一个jdbc声明
			Statement stmt = (Statement) conn.createStatement();
			DatabaseMetaData dbMeta = (DatabaseMetaData) conn.getMetaData();
			ResultSet rspk = dbMeta.getPrimaryKeys(null, null, tablename);
			String identity = null;
			while (rspk.next()) {
				identity = rspk.getString(4);
			}
			ResultSet columnSet = dbMeta.getColumns(null, "%", tablename, "%");
			Map mapCommont = new HashMap<String, String>();
			while (columnSet.next()) {
				mapCommont.put(columnSet.getString("COLUMN_NAME"), columnSet.getString("REMARKS"));
			}
			// 执行查询
			ResultSet rs = stmt.executeQuery(sql);
			ResultSetMetaData data = (ResultSetMetaData) rs.getMetaData();
			String hibStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
			hibStr += "<!DOCTYPE hibernate-mapping\r\n";
			hibStr += tab + "PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\"\r\n";
			hibStr += tab + "\"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\r\n";
			hibStr += "<!-- Hibernate映射文件的根元素 -->\r\n";
			hibStr += "<hibernate-mapping package=\"" + modelPackage + "\">\r\n";
			hibStr += tab + "<class name=\"" + baseName + "\" table=\"" + tablename + "\">";
			String modelStr = fileTop + "package " + modelPackage + ";\r\n\r\n[IMPORT]";
			String modelImport = "";
			modelStr += "\r\n/**\r\n * " + baseName + "Model\r\n * \r\n * @author " + author + "\r\n * @since " + dateStr + "\r\n */\r\n";
			modelStr += "public class " + baseName + " {\r\n";
			String modelAttr = "";
			String getSet = "";
			for (int i = 0; i < data.getColumnCount(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("INT", "int");
				map.put("TINYINT", "int");
				map.put("VARCHAR", "String");
				map.put("DATETIME", "Date");
				map.put("CHAR", "String");
				Map<String, String> hibmap = new HashMap<String, String>();
				hibmap.put("INT", "integer");
				hibmap.put("TINYINT", "integer");
				hibmap.put("VARCHAR", "string");
				hibmap.put("DATETIME", "timestamp");
				hibmap.put("CHAR", "string");
				String col = data.getColumnName(i + 1);
				String[] cols = col.split("_");
				String nCol = "";
				String typeName = data.getColumnTypeName(i + 1);
				String hibLong = "";
				if (!hibmap.get(typeName).equals("integer")) {
					int dataLong = data.getColumnDisplaySize(i + 1);
					hibLong = "length=\"" + dataLong + "\"";
				}
				if (typeName.equals("DATETIME") && modelImport.indexOf("import java.util.Date;") == -1) {
					modelImport += "import java.util.Date;\r\n";
				}
				for (int j = 0; j < cols.length; j++) {
					if (j > 0) {
						String str1 = cols[j].substring(0, 1);
						String str2 = cols[j].substring(1);
						nCol += this.setFirstToUpperCase(cols[j]);
					} else {
						nCol += cols[j];
					}
				}
				if (identity != null && col.equals(identity)) {
					hibStr += tab + tab + "<!-- 映射标识属性 -->\r\n";
					hibStr += tab + tab + "<id name=\"" + nCol + "\" type=\"" + hibmap.get(typeName) + "\" column=\"" + col + "\">\r\n";
					hibStr += tab + tab + tab + "<!-- 指定使用identity主键生成策略 -->\r\n";
					hibStr += tab + tab + tab + "<generator class=\"identity\" />\r\n";
					hibStr += tab + tab + "</id>\r\n";
				} else {
					hibStr += tab + tab + "<property name=\"" + nCol + "\" column=\"" + col + "\" type=\"" + hibmap.get(typeName) + "\" " + hibLong + "/>\r\n";
				}
				modelAttr += tab + "/** " + mapCommont.get(col) + " **/\r\n" + tab + "private " + map.get(typeName) + " " + nCol + ";\r\n";
				getSet += tab + "public " + map.get(typeName) + " get" + setFirstToUpperCase(nCol) + "() {\r\n" + tab + tab + "return " + nCol + ";\r\n" + tab + "}\r\n\r\n";
				getSet += tab + "public void set" + setFirstToUpperCase(nCol) + "(" + map.get(typeName) + " " + nCol + ") {\r\n" + tab + tab + "this." + nCol + " = " + nCol + ";\r\n" + tab + "}\r\n\r\n";
			}
			hibStr += tab + "</class>\r\n</hibernate-mapping>";
			modelStr = modelStr.replace("[IMPORT]", modelImport);
			modelStr += modelAttr;
			modelStr += "\r\n" + getSet;
			modelStr += "}";
			String modelFilePath = path + modelPackage.replace(".", "\\") + "\\" + baseName + ".java";
			File modelFile = new File(modelFilePath);
			if (modelFile.exists()) {
				modelFile.delete();
			}
			FileOutputStream fos = null;
			try {
				modelFile.createNewFile();
				fos = new FileOutputStream(modelFile);
				fos.write(modelStr.getBytes());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				fos.close();
			}
			String hibFilePath = path + modelPackage.replace(".", "\\") + "\\" + baseName + ".hbm.xml";
			File hibFile = new File(hibFilePath);
			if (hibFile.exists()) {
				hibFile.delete();
			}
			fos = null;
			try {
				hibFile.createNewFile();
				fos = new FileOutputStream(hibFile);
				fos.write(hibStr.getBytes());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				fos.close();
			}
			System.err.println(hibStr);
			System.out.println(modelStr);
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} finally {
			// 预防性关闭连接（避免异常发生时在try语句块关闭连接没有执行)
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
	}

	private String setFirstToUpperCase(String str) {
		String str1 = str.substring(0, 1);
		String str2 = str.substring(1);
		return str1.toUpperCase() + str2;
	}

	public static void main(String[] args) {
		AutoSSH testjdbc = new AutoSSH();
		try {
			testjdbc.test();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
